@(geneIds: Option[String],log2FcStr:Option[String])(implicit request: RequestHeader)
	@user.main("代谢物KEGG富集分析")("keggEnrich") {
		<style>
				.popover {
					max-width: 300px;
				}


		</style>
		<div class="page-content">

			<div class="page-bar">
				<ul class="page-breadcrumb">
					<li>
						<i class="fa fa-map-signs"></i>
						<a href="#">代谢物KEGG富集分析</a>
					</li>
				</ul>
			</div>


			<div class="row-fluid">

				<div class="row">
					<div class="col-md-12 col-sm-12">
						<div class="portlet green-jungle box">
							<div class="portlet-title">
								<div class="caption">
									设置参数
								</div>
							</div>

							<div class="portlet-body">

								<form class="registration-form" id="form"
								accept-charset="UTF-8" method="post">

									<div class="row">
										<div class="form-group  col-sm-3">
											<label class="control-label">输入提供方式: </label>
											<select class="form-control" name="offerMethod" id="offerMethod" onchange="change(this)">
												<option value="1">代谢物</option>
												<option value="2">代谢物+log2Fc</option>
											</select>
										</div>
									</div>

									<div class="row">
										<div class="col-sm-5">
											<div class="form-group">
												<label class="control-label">
													代谢物名称（一行代表一个代谢物，注意前后不要有空白字符）:
												</label>
												@if(geneIds.isDefined) {
													<textarea name="geneIdStr" id="geneId" class="form-control" rows="10">@geneIds.get</textarea>
												} else {
													<textarea name="geneIdStr" id="geneId" class="form-control" rows="10"></textarea>
												}
												<span class="help-block">e.g.,&nbsp;<a href="#"><em id="egGene">
													example</em></a></span>
											</div>
										</div>
										<div class="col-sm-4" id="log2FC" style="display: none">
											<div class="form-group">
												<label class="control-label">
													log2FC（一行代表一个代谢物对应的log2FC，注意前后不要有空白字符）:
												</label>
												@if(log2FcStr.isDefined) {
													<textarea name="log2FcStr"  class="form-control" rows="10">@log2FcStr.get</textarea>
												} else {
													<textarea name="log2FcStr"  class="form-control" rows="10"></textarea>
												}
											</div>
										</div>
									</div>

									<div class="row">
										<div class="form-group  col-sm-6">
											<label class="control-label">背景数据库:</label>
											<div class="input-group">
												<span class="input-group-addon"><em
												class="fa fa-book"></em></span>
												<select class="form-control" style="width: 30%"
												id="selectSpecies" required="required">
												</select>
												<select class="form-control" style="width: 70%"
												id="selectAnimal" name="library" required="required">
												</select>
											</div>
										</div>
									</div>

									<div class="row">
										<div class="form-group  col-sm-4">
											<label class="control-label">检验算法: </label>
											<select class="form-control" name="method">
												<option value="hyperg">Hypergeometric Test</option>
												<option value="fisher">Fisher's Exact Test</option>
											</select>
										</div>
									</div>

									<div class="row">
										<div class="form-group  col-sm-4">
											<label class="control-label">拓扑分析方法: </label>
											<select class="form-control" name="topMethod">
												<option value="rbc">Relative-betweeness Centrality</option>
												<option value="dgr">Out-degree Centrality</option>
											</select>
										</div>
									</div>

									<div class="row">
										<div class="form-group  col-sm-4">
											<label class="control-label">使用: </label>
											<select class="form-control" name="reference" id="chooseFile">
												<option value="all">Use all compounds in the selected pathways</option>
												<option value="self">
													Upload a reference metabolome based on your technical platform</option>
											</select>
										</div>
									</div>

									<div class="row" id="fileRow" style="display: none;">
										<div class="form-group col-sm-6">
											<label class="control-label">
												背景文件<span id="question2" style="margin-bottom: 5px;">
												<a type="button" title="说明" data-container="body" data-toggle="popover"
												data-placement="right" data-content="上传自定义背景信息文件，替换背景数据库。格式为制表符分隔的文本文件，每一行代表一个代谢物，总共两列，其中，第一列为代谢物名称，第二列为对应的KEGG数据库编号。例子：1-Methyluric acid(制表符)C16359 "
												data-trigger="hover"><i class="fa fa-question-circle-o"></i></a>
											</span>: </label>
											<input id="input-1" type="file" class="file control-label" name="file" data-show-preview="false"
											data-show-upload="false">
										</div>
									</div>

									<div class="row">
										<div class="form-group">
											<div class="actions col-sm-2">
												<button type="button" class="btn btn-primary" style="width: 90%;" id="search" onclick="mySearch()">
													运行</button>
											</div>

											<div class="actions  col-sm-2">
												<button type="reset" class="btn btn-primary" style="width: 90%;">
													重置</button>
											</div>
										</div>
									</div>


								</form>

							</div>
						</div>
					</div>
				</div>

				<div id="result" style="display: none">
					<div class="row">
						<div class="col-md-12 col-sm-12">
							<div class="portlet green-jungle box">
								<div class="portlet-title">
									<div class="caption">
										富集结果
									</div>
								</div>

								<div class="portlet-body" id="noCotent">暂无富集结果！</div>
								<div class="portlet-body" style="display: none;" id="content">
									<label>显示的列:</label>
									<div id="checkbox" class="checkbox">

									</div>

									<div class="table-responsive" id="tableContent">

										<table class="display table table-bordered" id="table" data-pagination="true" data-search="true"
										data-toolbar="#toolbar" data-page-list="[10, 25, 50, 100, all]" data-search-align="right" data-multiple-search="true"
										style="table-layout: fixed;
											word-wrap: break-word"
										data-show-export="true" data-export-types="['excel','txt']" data-export-data-type="all"
										>
											<thead>
												<tr>
													<th data-field='term' data-sortable='true' title="Term">Term</th>
													<th data-field='total' data-sortable='true' title="Total">
														Total</th>
													<th data-field='expected' data-sortable='true' title="Expected">
														Expected</th>
													<th data-field='hits' data-sortable='true' title="Hits">
														Hits</th>
													<th data-field='rawP' data-sortable='true' title="Raw p">
														Raw p</th>
													<th data-field='log' data-sortable='true' title="-log(p)">-log(p)</th>
													<th data-field='holm' data-sortable='true' title="Holm adjust">
														Holm adjust</th>
													<th data-field='fdr' data-sortable='true' title="FDR">FDR</th>
													<th data-field='impact' data-sortable='true' title="Impact">
														Impact</th>
													<th data-field='enrichCompound' data-sortable='true' title="EnrichCompound"
													data-formatter="mPipeFmt">
														EnrichCompound</th>
													<th data-field='link' data-sortable='true' title="Hyperlink">
														Hyperlink</th>
												</tr>
											</thead>
										</table>

									</div>

									<form class="registration-form form-horizontal" id="plotForm"
									accept-charset="UTF-8" method="post">

										<div class="form-group">
											<label class="control-label col-sm-1">Term:</label>
											<div class="col-sm-6" >
												<select class="form-control term" name="terms" id="term" multiple="multiple">

												</select>
											</div>
										</div>

										<div class="form-group">
											<div class="actions col-sm-offset-1 col-sm-1">
												<button type="button" class="btn btn-default" id="search" onclick="selectAll()" style="width: 80%">
													全选</button>
											</div>
											<div class="actions col-sm-1">
												<button type="button" class="btn btn-default" id="search" onclick="reverseSelect()" style="width: 80%">
													反选</button>
											</div>

											<div class="actions col-sm-1">
												<button type="button" class="btn btn-default" id="search" onclick="selectTop10()" style="width: 80%">
													top 10</button>
											</div>
											<div class="actions col-sm-1">
												<button type="button" class="btn btn-default" id="search" onclick="selectTop20()" style="width: 80%">
													top 20</button>
											</div>
										</div>

										<div class="form-group">
											<div class="actions col-sm-offset-1 col-sm-3">
												<button type="button" class="btn btn-primary" style="width: 90%;" id="search" onclick="plotBar()">
													富集结果柱状图（富集代谢物个数）</button>
											</div>
											<div class="actions  col-sm-3">
												<button type="button" class="btn btn-primary" style="width: 90%;" id="search" onclick="pie()">
													富集结果饼图（富集代谢物个数）</button>
											</div>
											<div class="actions  col-sm-3">
												<button type="button" class="btn btn-primary" style="width: 90%;" id="search" onclick="plotBar1()">
													富集结果柱状图（富集检验p值）</button>
											</div>
										</div>

										<hr style="border-top: 2px solid #eee;">

										<div id="charts" align="center">没有图片结果生成！</div>

									</form>

								</div>
							</div>
						</div>
					</div>

					<div class="row">
						<div class="col-md-12 col-sm-12">
							<div class="portlet green-jungle box">
								<div class="portlet-title">
									<div class="caption">
										引用
									</div>
								</div>
								<div class="portlet-body">
								<p class="paragraph">
									相关文献如下所示：
								</p>
									<p class="paragraph">
										Xia, J. and Wishart, D.S. (2016) Using MetaboAnalyst 3.0 for Comprehensive Metabolomics Data Analysis Current Protocols in Bioinformatics, 55:14.10.1-14.10.91.
									</p>
								</div>

							</div>
						</div>
					</div>
				</div>

			</div>

		</div>


		<script>
				var myData
				function mPipeFmt(value, row, index) {
					var proteins = value.split("|")
					var proteinStr = $.map(proteins, function (v) {
						return v
					}).join("&nbsp;|&nbsp;")
					return proteinStr
				}

				function change(element) {
					var value = $(element).find(">option:selected").val()
					if(value==1){
					    $("#log2FC").hide()
					}else{
						$("#log2FC").show()
					}
				}

				$(".file").fileinput({
					showPreview: false,
					browseLabel: "选择...",
					removeLabel: "删除",
					language: "zh"
				});

				function selectAll() {
					$("#term > option").prop("selected", "selected")
					$("#term").trigger("change");
					$("#plotForm").bootstrapValidator("revalidateField", "terms")
				}

				function selectTop20() {
					$("#term > option").prop("selected", false)
					$("#term").trigger("change")
					$("#term > option").slice(0, 20).prop("selected", "selected")
					$("#term").trigger("change");
					$("#plotForm").bootstrapValidator("revalidateField", "terms")
				}

				function selectTop10() {
					$("#term > option").prop("selected", false)
					$("#term").trigger("change")
					$("#term > option").slice(0, 10).prop("selected", "selected")
					$("#term").trigger("change")
					$("#plotForm").bootstrapValidator("revalidateField", "terms")
				}

				function reverseSelect() {
					$("#term > option").prop("selected", false)
					$("#term").trigger("change");
					$("#plotForm").bootstrapValidator("revalidateField", "terms")
				}

				function plotBar1() {
					var form = $("#plotForm")
					var fv = form.data("bootstrapValidator")
					fv.validate()
					if (fv.isValid()) {
						var element = "<div id='content'><span id='info'>" + zhRunning + "</span>&nbsp;<img class='runningImage' src='@routes.Assets.at("images/running2.gif")' style='width: 30px;height: 20px;'></div>"
						var index = layer.alert(element, {
							skin: 'layui-layer-molv'
							, closeBtn: 0,
							title: zhInfo,
							btn: []
						});
						var terms = $("#term").val()
						var tmpDatas = $.grep(myData, function (v) {
							return $.inArray(v.term, terms) >= 0
						})
						var numbers = $.map(tmpDatas, function (v) {
							return v.rawP
						})
						$.ajax({
							url: "@routes.MetaboliteController.pBarPlot()",
							type: "post",
							data: {
								terms: $("#term").val(),
								datas: numbers
							},
							success: function (data) {
								layer.close(index)
								if (data.valid == "false") {
									$("#charts").html("没有图片结果生成！")
									swal("Error", data.message, "error")
								} else {
									$("#charts").html(data.div)
								}

							}
						});
					}
				}

				function pie() {
					var form = $("#plotForm")
					var fv = form.data("bootstrapValidator")
					fv.validate()
					if (fv.isValid()) {
						var element = "<div id='content'><span id='info'>" + zhRunning + "</span>&nbsp;<img class='runningImage' src='@routes.Assets.at("images/running2.gif")' style='width: 30px;height: 20px;'></div>"
						var index = layer.alert(element, {
							skin: 'layui-layer-molv'
							, closeBtn: 0,
							title: zhInfo,
							btn: []
						});
						var terms = $("#term").val()
						var tmpDatas = $.grep(myData, function (v) {
							return $.inArray(v.term, terms) >= 0
						})
						var numbers = $.map(tmpDatas, function (v) {
							return v.hits
						})
						$.ajax({
							url: "@routes.MetaboliteController.pie()",
							type: "post",
							data: {
								terms: $("#term").val(),
								datas: numbers
							},
							success: function (data) {
								layer.close(index)
								if (data.valid == "false") {
									$("#charts").html("没有图片结果生成！")
									swal("Error", data.message, "error")
								} else {
									$("#charts").html(data.div)
								}
							}
						});
					}
				}

				$(function () {
				    @if(log2FcStr.isDefined){
					$("#offerMethod").val("2").trigger("change")
					}


					$(".term").select2()

					//选择引用文件触发触发
					$("#chooseFile").on("change", function () {
						var chooseFile = $("#chooseFile>option:selected").val();
						if (chooseFile == "self") {
							$("#fileRow").css("display", "block");
						} else {
							$("#fileRow").css("display", "none");
						}
					});

					var species = [];
					species[0] = "Mammals";
					species[1] = "Birds";
					species[2] = "Fish";
					species[3] = "Insects";
					species[4] = "Nematodes";
					species[5] = "Fungi";
					species[6] = "Plants";
					species[7] = "Parasites";
					species[8] = "Prokaryotes";
					for (var i = 0; i < species.length; i++) {
						$("#selectSpecies").append(
								"<option value=" + species[i] + ">" + species[i]
								+ "</option>");
					}

					var animal = [];
					animal[0] = ["Homo sapiens (human) [80]", "Mus musculus (mouse) [82]", "Rattus norvegicus (rat) [81]", "Bos taurus (cow) [81]"];
					animal[1] = ["Gallus gallus (chicken) [78]"];
					animal[2] = ["Danio rerio (zebrafish) [81]"];
					animal[3] = ["Drosophila melanogaster (fruit fly) [79]"];
					animal[4] = ["Caenorhabditis elegans (nematode) [78]"];
					animal[5] = ["Saccharomyces cerevisiae (yeast) [65]"];
					animal[6] = ["Oryza sativa japonica (Japanese rice) [83]", "Arabidopsis thaliana (thale cress) [87]"];
					animal[7] = ["Schistosoma mansoni [69]", "Plasmodium falciparum 3D7 (Malaria) [47]", "Trypanosoma brucei [54]"];
					animal[8] = ["Escherichia coli K-12 MG1655 [87]", "Bacillus subtilis [80]", "Pseudomonas putida KT2440 [89]", "Staphylococcus aureus N315 (MRSA/VSSA) [73]", "Thermotoga maritima [57]", "Synechococcus elongatus PCC7942 [75]", "Mesorhizobium loti [86]"];
					var animalValue = []
					animalValue[0] = ["hsa", "mmu", "rno", "bta"]
					animalValue[1] = ["gga"]
					animalValue[2] = ["dre"]
					animalValue[3] = ["dme"]
					animalValue[4] = ["cel"]
					animalValue[5] = ["sce"]
					animalValue[6] = ["osa", "ath"]
					animalValue[7] = ["smm", "pfa", "tbr"]
					animalValue[8] = ["eco", "bsu", "ppu", "sau", "tma", "syf", "mlo"]
					for (var i = 0; i < animal[0].length; i++) {
						$("#selectAnimal")
								.append(
										"<option value="
										+ animalValue[0][i]
										+ ">"
										+ animal[0][i]
										+ "</option>");
					}
					$("#selectSpecies")
							.on(
									"change",
									function () {
										//noinspection JSValidateTypes
										$("#selectAnimal").children("option")
												.detach();
										var indexProv = $(
												"#selectSpecies>option:selected")
												.index();// 取得选中的想的数组下标0
										for (var i = 0; i < animal[indexProv].length; i++) {
											$("#selectAnimal")
													.append(
															"<option value="
															+ animalValue[indexProv][i]
															+ ">"
															+ animal[indexProv][i]
															+ "</option>");
										}
									});


					$('#egGene').click(function () {
						$.ajax({
							url: "@routes.MetaboliteController.getFirst10GeneIdByLf()",
							type: "get",
							success: function (data) {
								$('#geneId').val(data);
								$("#form").bootstrapValidator("revalidateField", "geneIdStr")
								return false
							}
						})
					});

					$.ajax({
						url: "@routes.MetaboliteController.getGeneIds()",
						type: "get",
						success: function (data) {
							$('#geneId').typeahead({
								source: data.geneIds,
								updater: function (item) {
									return this.$element.val().replace(matcherRegex, '') + item + matcherEnd;
								},
								matcher: function (item) {
									var tquery = extractor(this.query);
									if (!tquery) return false;
									return ~item.toLowerCase().indexOf(tquery.toLowerCase())
								},
								highlighter: function (item) {
									var query = extractor(this.query).replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
									return item.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
										return '<strong>' + match + '</strong>'
									})
								}
							})
						}
					})

					var array = ["Total", "Expected", "Hits", "Raw p", "-log(p)", "Holm adjust", "FDR", "Impact", "EnrichCompound", "Hyperlink"]
					var values = ["total", "expected", "hits", "rawP", "log", "holm", "fdr", "impact", "enrichCompound", "link"]
					var html = ""
					$.each(array, function (n, value) {
								html += "<label style='margin-right: 15px'>" +
										"<input type='checkbox' checked='checked' value='" + values[n] + "' onclick=\"setColumns('" + values[n] + "')\">" + value +
										"</label>"
							}
					);
					$("#checkbox").append(html)
					$('#table').bootstrapTable({
						exportOptions: {
							csvSeparator: "\t",
							onCellHtmlData: function (cell, row, col, htmlData) {
								var value
								var html = $.parseHTML(htmlData)
								if ($(html).text() == "link") {
									value = $(html).attr("href")
								} else {
									value = $(html).text()
								}
								return value
							}
						},

					});

					var hiddenArray = ["fdr", "log", "holm"]
					$.each(hiddenArray, function (n, value) {
								$('#table').bootstrapTable('hideColumn', value);
								$("input:checkbox[value=" + value + "]").attr("checked", false)
							}
					);


					bootstrapValidator()
				})


				function mySearch() {
					var form = $("#form")
					var fv = form.data("bootstrapValidator")
					fv.validate()
					if (fv.isValid()) {
						var element = "<div id='content'><span id='info'>" + zhRunning + "</span>&nbsp;<img class='runningImage' src='@routes.Assets.at("images/running2.gif")' style='width: 30px;height: 20px;'></div>"
						var index = layer.alert(element, {
							skin: 'layui-layer-molv'
							, closeBtn: 0,
							title: zhInfo,
							btn: []
						});
						var form1 = new FormData($("#form")[0])
						$.ajax({
							url: "@routes.MetaboliteController.keggEnrich()",
							type: "post",
							processData: false,
							contentType: false,
							data: form1,
							success: function (data) {
								layer.close(index)
								if (data.valid == "false") {
									$("#noCotent").show()
									$("#content").hide()
									swal("Error", data.message, "error")
									$("#result").hide()
								} else {
									$("#noCotent").hide()
									$("#content").show()
									$("#result").show()
									$('#table').bootstrapTable("load", data);
									myData = data
									var terms = $.map(data, function (v) {
										return v.term
									})
									$(".term").select2({
										data: terms,
										placeholder: "点击选择",
										allowClear: true
									})
								}
							}
						});
					}
				}

				function plotBar() {
					var form = $("#plotForm")
					var fv = form.data("bootstrapValidator")
					fv.validate()
					if (fv.isValid()) {
						var element = "<div id='content'><span id='info'>" + zhRunning + "</span>&nbsp;<img class='runningImage' src='@routes.Assets.at("images/running2.gif")' style='width: 30px;height: 20px;'></div>"
						var index = layer.alert(element, {
							skin: 'layui-layer-molv'
							, closeBtn: 0,
							title: zhInfo,
							btn: []
						});
						var terms = $("#term").val()
						var tmpDatas = $.grep(myData, function (v) {
							return $.inArray(v.term, terms) >= 0
						})
						var numbers = $.map(tmpDatas, function (v) {
							return v.hits
						})
						$.ajax({
							url: "@routes.MetaboliteController.barPlot()",
							type: "post",
							data: {
								terms: $("#term").val(),
								datas: numbers
							},
							success: function (data) {
								layer.close(index)
								if (data.valid == "false") {
									$("#charts").html("没有图片结果生成！")
									swal("Error", data.message, "error")
								} else {
									$("#charts").html(data.div)
								}
							}
						});
					}
				}

				function bootstrapValidator() {
					var infinityNumber = Number.MAX_VALUE
					$('#form').bootstrapValidator({
						framework: 'bootstrap',
						icon: {
							valid: 'glyphicon glyphicon-ok',
							invalid: 'glyphicon glyphicon-remove',
							validating: 'glyphicon glyphicon-refresh'
						},
						fields: {
							geneIdStr: {
								validators: {
									notEmpty: {
										message: '代谢物名称不能为空！'
									},
								}
							},
							file: {
								validators: {
									notEmpty: {
										message: '请选择一个代谢物引用文件！'
									},
									file: {
										extension: 'txt',
										message: '请选择一个TXT格式的代谢物引用文件！'
									}
								}
							},
							log2FcStr: {
								validators: {
									notEmpty: {
										message: 'log2FC不能为空！'
									},
								}
							},

						}
					});

					$('#plotForm').bootstrapValidator({
						framework: 'bootstrap',
						icon: {
							valid: 'glyphicon glyphicon-ok',
							invalid: 'glyphicon glyphicon-remove',
							validating: 'glyphicon glyphicon-refresh'
						},
						fields: {
							terms: {
								validators: {
									callback: {
										message: '请至少选择一个Term！',
										callback: function (value, validator, $field) {
											var options = validator.getFieldElements('terms').val();
											return (options != null);
										}
									}
								}
							},
						}
					});

				}

				function setColumns(value) {
					var element = $("input:checkbox[value=" + value + "]")
					if (element.is(":checked")) {
						$('#table').bootstrapTable('showColumn', value);
					} else {
						$('#table').bootstrapTable('hideColumn', value);
					}
				}

		</script>

	}